package sftd;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;

public class SFTD extends JPanel {

	private static final long serialVersionUID = 6783113737417873462L;
	
	private Tower towers[][];
	
	public SFTD() {
		setPreferredSize(new Dimension(1024, 768));
		
		towers = new Tower[24][24];
		
		try {
			Tower.TowerType type = new Tower.TowerType(
					ImageIO.read(new File("testBase.png")),
					ImageIO.read(new File("testCannon.png"))
			);
			
			towers[8][12] = new Tower(type);
			towers[10][4] = new Tower(type);
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		(new Timer(1000 / 16, new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				towers[8][12].setRotation(towers[8][12].getRotation() + 0.03f);
				towers[10][4].setRotation(towers[10][4].getRotation() - 0.05f);
				repaint();
			}
		})).start();
	}
	
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		paintScene((Graphics2D)g);
	}
	
	private void paintScene(Graphics2D g) {
		g.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
		g.setRenderingHints(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR));

		// Grid color
		g.setColor(new Color(g.getBackground().getRed() - 8, g.getBackground().getGreen() - 8, g.getBackground().getBlue() - 8));
		
		for(int x = 0, x32 = 0; x < 24; ++x, x32 += 32) {
			for(int y = 0, y32 = 0; y < 24; ++y, y32 += 32) {
				g.drawRect(x32, y32, 31, 31);
				
				Tower tower = towers[x][y];
				if(tower != null) {
					AffineTransform transform = AffineTransform.getTranslateInstance(x32, y32);
					transform.rotate(tower.getRotation(), 16.0, 16.0);
					
					g.drawImage(tower.getType().getBaseImage(), x32, y32, 32, 32, null);
					g.drawImage(tower.getType().getCannonImage(), transform, null);
				}
			}
		}
	}

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		JFrame frame = new JFrame("SciFi Tower Defense");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(new SFTD());
		frame.pack();
		frame.setVisible(true);
	}
}
